package cn.fl.insurance.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.condition.InsChnOpenSettingQueryCondition;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.insurance.dto.InsChnOpenSettingDTO;
import cn.fl.insurance.service.IInsChnOpenSettingApiService;
import cn.fl.insurance.service.IInsChnOpenSettingService;
import cn.fl.insurance.service.IInsTypInfoService;
import cn.fl.insurance.transform.InsChnOpenSettingVOTransform;
import cn.fl.insurance.vo.InsChnOpenSettingVO;
import cn.fl.insurance.vo.OrgTreeVO;
import cn.fl.insurance.vo.ReginTreeVO;

/**
 * @Description: 渠道放开设置表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class InsChnOpenSettingServiceImpl implements IInsChnOpenSettingService {

    /**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(InsChnOpenSettingServiceImpl.class);

    /**
     * 渠道放开设置表 暴露服务
     */
    @Autowired
    private IInsChnOpenSettingApiService insChnOpenSettingApiService;
    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysRegionApiService sysRegionApiService;
    @Autowired
    private ISysOrgApiService sysOrgApiService;
    @Autowired
    private IInsTypInfoService insTypInfoService;

    @Override
    public InsChnOpenSettingVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) return null;
        InsChnOpenSettingDTO dto = this.insChnOpenSettingApiService.selectInsChnOpenSettingById(id);
        return InsChnOpenSettingVOTransform.toVO(dto);
    }

    @Override
    public Long add(InsChnOpenSettingVO entity) throws BaseException {
        if (null == entity) return null;
        return this.insChnOpenSettingApiService.addInsChnOpenSetting(InsChnOpenSettingVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) return false;
        return this.insChnOpenSettingApiService.removeInsChnOpenSettingByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

    @Override
    public boolean modify(InsChnOpenSettingVO entity) throws BaseException {
        if (null == entity) return false;
        return this.insChnOpenSettingApiService.modifyInsChnOpenSetting(InsChnOpenSettingVOTransform.toDTO(entity));
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        InsChnOpenSettingQueryCondition condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new InsChnOpenSettingQueryCondition());
        }
        condition = (InsChnOpenSettingQueryCondition) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        page = this.insChnOpenSettingApiService.searchInsChnOpenSettingListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<InsChnOpenSettingVO> voList = InsChnOpenSettingVOTransform.toVOList((List<InsChnOpenSettingDTO>) page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    @Override
    public List<InsChnOpenSettingVO> searchList(InsChnOpenSettingQueryCondition condition) throws BaseException {
        if (null == condition) condition = new InsChnOpenSettingQueryCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        List<InsChnOpenSettingVO> voList = InsChnOpenSettingVOTransform.toVOList(this.insChnOpenSettingApiService.searchInsChnOpenSettingList(condition));
        //this.setDictData(voList);
        return voList;
    }

    /**
     * 添加数据字典名称
     *
     * @param voList
     */
    public void setDictData(List<InsChnOpenSettingVO> voList) {
        if (CollectionUtils.isEmpty(voList)) return;
        Map<String, String> prjTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_PRJ_TYP_CD);
        if (CollectionUtils.isMapEmpty(prjTypCdMap)) {
            prjTypCdMap = new HashMap<>(1);
        }
        prjTypCdMap.put("ALL", "全部");
        Map<String, String> bizTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_PRJ_BIZ_TYP_CD);
        if (CollectionUtils.isMapEmpty(bizTypCdMap)) {
            bizTypCdMap = new HashMap<>(1);
        }
        bizTypCdMap.put("ALL", "全部");
        Map<String, String> plcTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_INS_PLC_NAT_CD);
        if (CollectionUtils.isMapEmpty(plcTypCdMap)) {
            plcTypCdMap = new HashMap<>(1);
        }
        plcTypCdMap.put("ALL", "全部");
        Map<String, String> enableCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_ENABLE_ON_OFF_CD);
        /*InsTypInfoQueryCondition condition = new InsTypInfoQueryCondition();
        condition.setTypLvl(InsuranceConstant.CODE_INS_TYP_LVL_CD);//保险父类
        Map<String, String> insTypCdMap = this.insTypInfoService.searchInsTypCdMap(condition);//保险父类*/
        Map<String, String> insTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_INS_TYP_CD);
        if (CollectionUtils.isMapEmpty(insTypCdMap)) {
            insTypCdMap = new HashMap<>(1);
        }
        insTypCdMap.put("ALL", "全部");

        /*List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
        Map<String, String> buOrgCdMap = null;
        if (CollectionUtils.isNotEmpty(list)) {
            buOrgCdMap = new HashMap<>(list.size() + 1);
            for (SysOrgDTO sysOrgDTO : list) {
                buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO.getOrgNm());
            }
        } else {
            buOrgCdMap = new HashMap<>(1);
        }
        buOrgCdMap.put("ALL", "全部");

        Map<String, String> rgnCdMap = this.searchReginMap();*/

        for (InsChnOpenSettingVO vo : voList) {
            if (prjTypCdMap != null) {
                if (StringUtils.isNotBlank(vo.getPrjTypCd())) {
                    String[] prjTypCdArray = vo.getPrjTypCd().split(";");
                    StringBuffer prjTypCdNm = new StringBuffer("");
                    for (String prjTypCd : prjTypCdArray) {
                        if (prjTypCdMap.containsKey(prjTypCd)) {
                            prjTypCdNm.append(prjTypCdMap.get(prjTypCd));
                        } else {
                            prjTypCdNm.append(prjTypCd);
                        }
                        prjTypCdNm.append("、");
                    }
                    vo.setPrjTypCdNm(prjTypCdNm.toString().substring(0, prjTypCdNm.toString().length() - 1));
                }
            }
            if (bizTypCdMap != null) {
                if (StringUtils.isNotBlank(vo.getBizTypCd())) {
                    String[] bizTypCdArray = vo.getBizTypCd().split(";");
                    StringBuffer bizTypCdNm = new StringBuffer("");
                    for (String bizTypCd : bizTypCdArray) {
                        if (bizTypCdMap.containsKey(bizTypCd)) {
                            bizTypCdNm.append(bizTypCdMap.get(bizTypCd));
                        } else {
                            bizTypCdNm.append(bizTypCd);
                        }
                        bizTypCdNm.append("、");
                    }
                    vo.setBizTypCdNm(bizTypCdNm.toString().substring(0, bizTypCdNm.toString().length() - 1));
                }
            }
            if (plcTypCdMap != null) {
                if (StringUtils.isNotBlank(vo.getPlcTypCd())) {
                    String[] plcTypCdArray = vo.getPlcTypCd().split(";");
                    StringBuffer plcTypCdNm = new StringBuffer("");
                    for (String plcTypCd : plcTypCdArray) {
                        if (plcTypCdMap.containsKey(plcTypCd)) {
                            plcTypCdNm.append(plcTypCdMap.get(plcTypCd));
                        } else {
                            plcTypCdNm.append(plcTypCd);
                        }
                        plcTypCdNm.append("、");
                    }
                    vo.setPlcTypCdNm(plcTypCdNm.toString().substring(0, plcTypCdNm.toString().length() - 1));
                }
            }
            if (enableCdMap != null && enableCdMap.containsKey(String.valueOf(vo.getIsValid()))) {
                vo.setStatus(enableCdMap.get(String.valueOf(vo.getIsValid())));
            }
            if (insTypCdMap != null) {
                if (StringUtils.isNotBlank(vo.getInsTypCd())) {
                    String[] insTypCdArray = vo.getInsTypCd().split(";");
                    StringBuffer insTypCdNm = new StringBuffer("");
                    for (String insTypCd : insTypCdArray) {
                        if (insTypCdMap.containsKey(insTypCd)) {
                            insTypCdNm.append(insTypCdMap.get(insTypCd));
                        } else {
                            insTypCdNm.append(insTypCd);
                        }
                        insTypCdNm.append("、");
                    }
                    vo.setInsTypCdNm(insTypCdNm.toString().substring(0, insTypCdNm.toString().length() - 1));
                }
            }
            /*if (buOrgCdMap != null) {
                if (StringUtils.isNotBlank(vo.getBuOrgCd())) {
                    String[] buOrgCdArray = vo.getBuOrgCd().split(";");
                    StringBuffer buOrgCdNm = new StringBuffer("");
                    for (String buOrgCd : buOrgCdArray) {
                        if (buOrgCdMap.containsKey(buOrgCd)) {
                            buOrgCdNm.append(buOrgCdMap.get(buOrgCd));
                        } else {
                            buOrgCdNm.append(buOrgCd);
                        }
                        buOrgCdNm.append("、");
                    }
                    vo.setBuOrgCdNm(buOrgCdNm.toString().substring(0, buOrgCdNm.toString().length() - 1));
                }
            }

            if (rgnCdMap != null) {
                if (StringUtils.isNotBlank(vo.getRgnCd())) {
                    String[] rgnCdArray = vo.getRgnCd().split(";");
                    StringBuffer rgnCdNm = new StringBuffer("");
                    for (String rgnCd : rgnCdArray) {
                        if (rgnCdMap.containsKey(rgnCd)) {
                            rgnCdNm.append(rgnCdMap.get(rgnCd));
                        } else {
                            rgnCdNm.append(rgnCd);
                        }
                        rgnCdNm.append("、");
                    }
                    vo.setRgnCdNm(rgnCdNm.toString().substring(0, rgnCdNm.toString().length() - 1));
                }
            }*/
        }
    }

    /**
     * 查询数据字典
     *
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchCdList(String groupCd) throws BaseException {
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 查询地区树
     *
     * @return
     */
    @Override
    public List<ReginTreeVO> searchReginTreeVOList() throws BaseException {
        ReginTreeVO country = new ReginTreeVO();
        country.setRgnCd("0,0,0");
        country.setRgnNm("全国");
        List<ReginTreeVO> countryRgnList = new ArrayList<>();
        List<SysRegionDTO> prList = sysRegionApiService.searchProvinceList(CurrentThreadContext.getCurrentSysCd());
        ReginTreeVO prVO = null;
        ReginTreeVO cyVO = null;
        for (SysRegionDTO pr : prList) {
            prVO = new ReginTreeVO();
            prVO.setRgnCd("0," + pr.getRgnCd() + ",0");
            prVO.setRgnNm(pr.getRgnNm());
            List<SysRegionDTO> cyList = sysRegionApiService.searchRegineByRgnPid(pr.getId(), CurrentThreadContext.getCurrentSysCd());
            List<ReginTreeVO> cyRgnList = new ArrayList<>();
            for (SysRegionDTO city : cyList) {
                cyVO = new ReginTreeVO();
                cyVO.setRgnCd("0," + pr.getRgnCd() + "," + city.getRgnCd());
                cyVO.setRgnNm(city.getRgnNm());
                cyRgnList.add(cyVO);
            }
            prVO.setChildren(cyRgnList);
            countryRgnList.add(prVO);
        }
        country.setChildren(countryRgnList);
        List<ReginTreeVO> voList = new ArrayList<>();
        voList.add(country);
        return voList;
    }

    /**
     * 查询地区Map
     *
     * @return
     */
    private Map<String, String> searchReginMap() throws BaseException {
        Map<String, String> map = new HashMap<>();
        map.put("0,0,0", "全国");
        List<ReginTreeVO> countryRgnList = new ArrayList<>();
        List<SysRegionDTO> prList = sysRegionApiService.searchProvinceList(CurrentThreadContext.getCurrentSysCd());
        for (SysRegionDTO pr : prList) {
            map.put("0," + pr.getRgnCd() + ",0", pr.getRgnNm());
            List<SysRegionDTO> cyList = sysRegionApiService.searchRegineByRgnPid(pr.getId(), CurrentThreadContext.getCurrentSysCd());
            for (SysRegionDTO city : cyList) {
                map.put("0," + pr.getRgnCd() + "," + city.getRgnCd(), city.getRgnNm());
            }
        }
        return map;
    }


    /**
     * 查询机构树
     *
     * @return
     */
    @Override
    public List<OrgTreeVO> searchOrgTreeVOList(Long orgId) throws BaseException {
        List<SysOrgDTO> orgList = null;
        if (StringUtils.isNotEmpty(orgId)) {
            orgList = this.sysOrgApiService.searchSysOrgByOrgPid(orgId, CurrentThreadContext.getCurrentSysCd());
        }else{
            orgList = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
        }
        List<OrgTreeVO> list = null;
        if(CollectionUtils.isNotEmpty(orgList)){
            list = new ArrayList<>(orgList.size());
            OrgTreeVO orgTreeVO;
            for (SysOrgDTO org : orgList) {
                orgTreeVO=new OrgTreeVO();
                orgTreeVO.setOrgCd(org.getOrgCd());
                orgTreeVO.setId(org.getId());
                orgTreeVO.setOrgNm(org.getOrgDispNm());
                orgTreeVO.setPid(org.getOrgPid());
                orgTreeVO.setChildren(searchOrgTreeVOList(org.getId()));
                list.add(orgTreeVO);
            }
        }
        return list;
    }

}
